package com.ksl.kinglockguard.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import com.ksl.kinglockguard.network.NetworkTask;
import com.ksl.kinglockguard.network.appupdate.AppUpdateFileUtil;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.utils.ProductInfoUtils;


/**
 * 进程复活 
 */
public class KingsReviveMain {
	private static final String DaemonProcessName = "kinglock_daemon";

	public static void main(String[] args) {
		Method setArgV0;
		try {
			setArgV0 = android.os.Process.class.getDeclaredMethod("setArgV0",
					new Class[] { String.class });
			setArgV0.setAccessible(true);
			setArgV0.invoke(android.os.Process.class,
					new Object[] { DaemonProcessName });
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		// 主进程ID
		final int hostProcessID;
		String path = "";
		HashMap<String,String> map = new HashMap<String, String>();
		if (args.length > 0) {
			try {
				hostProcessID = Integer.parseInt(args[0]);
				MyLog.d(DaemonProcessName, "host pid:" + hostProcessID);
				if(args.length > 5){
					path = args[1];
					String imei =args[2];
					map.put("imei", imei);
					String channel =args[3];
					map.put("channel", channel);
					String vcode =args[4];
					map.put("vcode", vcode);
					String mc =args[5];
					map.put("mc", mc);
				}
			} catch (NumberFormatException e) {
				MyLog.d(DaemonProcessName, "UnKnow pid");
				return;
			}
		} else {
			MyLog.d(DaemonProcessName, "Args not find");
			return;
		}
		boolean isUpdate= false;
		int uploadNum =0;
		while (true) {
			MyLog.d(DaemonProcessName, " RebootMain******");
			try {
				File hostProcess = new File("/proc/" + hostProcessID);
				if (!hostProcess.exists()) {
					File hostPname = new File("/data/data/com.ksl.kinglockguard");
					if(!hostPname.exists()){
						try {
							uploadNum++;
							HttpURLConnection connetction =NetworkTask.countUninstallEvent(map, 5000);
							Thread.sleep(6000);
							if(connetction.getResponseCode()==200){
								MyLog.d(DaemonProcessName, " RebootMain******OK");
								android.os.Process.killProcess(android.os.Process.myPid());
							}
						} catch (IOException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(uploadNum>2){
							android.os.Process.killProcess(android.os.Process.myPid());
						}
						Thread.sleep(10000);
					}else{
						// 证明主进程已经被kill掉，所以重新启动服务
						MyLog.d(DaemonProcessName, "start cmdLine ******"+hostProcessID);
						String cmdLine = "am startservice --user 0 -a com.kingsgame.lock.kingsdaemon.self";
						if (Build.VERSION.SDK_INT <= 15) {
							cmdLine = "am startservice -a com.kingsgame.lock.kingsdaemon.self";
						}
						try {
							Runtime.getRuntime().exec(cmdLine);
						} catch (IOException e) {
							e.printStackTrace();
						}
						MyLog.d(DaemonProcessName, "killed myself---------");
						android.os.Process.killProcess(android.os.Process.myPid());
					}
					
					
				}
				Thread.sleep(10000);// todo ydy 十秒
				
				// lijc add start 
				if(TextUtils.isEmpty(path)){
					continue;
				}
				File file = new File(path);
				MyLog.d(DaemonProcessName, "install apk---------file exists: "+file.getAbsolutePath() + " ;;exists: " + file.exists());
				if(!isUpdate && file.exists()){
					File end = new File(path+"/"+END_APK);
					MyLog.d(DaemonProcessName, "install apk---------end: "+end.getAbsolutePath() + " ;;end.exists: " + end.exists());
					File update = new File(path+"/"+UPDATE_APK);
					MyLog.d(DaemonProcessName, "install apk---------update: "+update.getAbsolutePath() + " ;;update.exists: " + update.exists());
					if(end.exists()&&update.exists()){
						isUpdate=true;
						String updatepath = update.getAbsolutePath();
						
						MyLog.d(DaemonProcessName, "install apk---------upFlag path=="+updatepath);              
						String[] vCmds = new String[]{
								"pm install -r -l "+updatepath
						};
						try {
							
							MyLog.d(DaemonProcessName, "install myself---------" + Arrays.toString(vCmds));
							for(String cmd:vCmds){
								MyLog.d(DaemonProcessName, "install myself---------cmd : " + cmd);
								String result=KingsExecuteRoot.getExecuteRoot(true).runCommand(cmd);
								MyLog.d(DaemonProcessName, "install myself---------result=="+result);
							}
							Thread.sleep(5000);
							end.delete();
							update.delete();
							file.delete();
							isUpdate=false;
						} catch (Exception e) {
							MyLog.e(DaemonProcessName, "install myself---------Exception :  " + e);
							e.printStackTrace();
						}
					}
					
				}
				//lijc add end
			} catch (InterruptedException e) {
			}
		}
	}

	/**
	 * 得到应用守护进程的ID
	 */
	public static int getDaemonProcessID() {
		for (File processDir : getAllProcessDirs()) {
			BufferedReader br = null;
			try {
				br = new BufferedReader(new InputStreamReader(
						new FileInputStream(new File(processDir, "cmdline"))));
				String processName = br.readLine();
				MyLog.i("wmm", "interateor name is "+processName);
				if (processName == null) {
					continue;
				}
				processName = processName.trim();
				if (DaemonProcessName.equals(processName)) {
					MyLog.i("wmm", "process name is "+processName);
					try {
						return Integer.parseInt(processDir.getName());
					} catch (NumberFormatException e) {
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (br != null) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return -1;
	}

	private static File[] getAllProcessDirs() {
		File procDir = new File("/proc");
		return procDir.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				try {
					Integer.parseInt(pathname.getName());
					return true;
				} catch (NumberFormatException e) {
					return false;
				}
			}
		});
	}
	public static final String UPDATE_APK="blueFlash.apk";
	public static final String END_APK="end.apk";
	public static void startDaemonProcess(Context context) {
/*		MyLog.d(DaemonProcessName, "startDaemonProcess");
		
		int daemonPid = getDaemonProcessID();
		if (daemonPid == -1) {
			try {
				// System.getenv()读取系统环境变量
				Map<String, String> envMap = new HashMap<String, String>(
						System.getenv());
				
				envMap.put("CLASSPATH", 
						context.getApplicationInfo().sourceDir);
				String[] envs = new String[envMap.size()];
				int index = 0;
				for (Entry<String, String> entry : envMap.entrySet()) {
					envs[index++] = entry.getKey() + "=" + entry.getValue();
				}
				// app_process用于启动java类,最终会调main函数
				String path = AppUpdateFileUtil.getRootUpdateAppPath();
				
				Runtime.getRuntime().exec(
						"/system/bin/app_process /system/bin "
								+ KingsReviveMain.class.getName() + " "
								+ android.os.Process.myPid() + " " + path+ 
								" "+ProductInfoUtils.getIMEI(context)+
								" "+ProductInfoUtils.getChannelName(context)+
								" "+ProductInfoUtils.getVcode(context)+
								" "+ProductInfoUtils.getVcode(context)+
								 "\n", envs);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
*/		
	}

	/**
	 * 停止守护进程
	 */
	public static void stopDaemonProcess() {
		int daemonPid = getDaemonProcessID();
		if (daemonPid != -1) {
			android.os.Process.killProcess(daemonPid);
		}
	}
}
